<template>
  <div class="app-container">
    <!-- 分配角色数据权限对话框 -->
    <el-dialog :title="prop.title" :visible="prop.open" width="500px" append-to-body :show-close="false">
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.roleName" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限字符">
          <el-input v-model="form.roleKey" :disabled="true" />
        </el-form-item>
        <el-form-item label="权限范围">
          <el-select v-model="form.roleDataScope" @change="dataScopeSelectChange">
            <el-option
              v-for="item in dataScopeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据权限" v-show="form.roleDataScope == 2">
          <el-checkbox v-model="organizationExpand" @change="handleCheckedTreeExpand($event, 'organization')">展开/折叠</el-checkbox>
          <el-checkbox v-model="organizationNodeAll" @change="handleCheckedTreeNodeAll($event, 'organization')">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.organizationCheckStrictly" @change="handleCheckedTreeConnect($event, 'organization')">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="organizationOptions"
            show-checkbox
            default-expand-all
            ref="organization"
            node-key="organizationSysCode"
            :check-strictly="!form.organizationCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {dataScopeOptions} from "@/utils/constants/common/constants.js"
import {getDetail,editDataScope} from "@/api/system/role";
import { getOrganizationsSelectItems } from "@/api/organization/organization/organization.js";
export default {
  name: "tmp",
  components: {  },
  props:{
    prop:{
      type:Object,
      default:function(){
        return {
          open:false,
          title:'角色数据权限',
          roleId:null
        }
      }
    }
  },
  data() {
    return {
      organizationExpand: true,
      organizationNodeAll: false,
      organizationOptions: [],
      dataScopeOptions:dataScopeOptions,
      defaultProps: {
        children: "children",
        label: "organizationName"
      },
      form:{
        roleId:null,
        roleDataScope:null,
        roleOrganizations:null,
      },
    };
  },
  methods: {
    handleCheckedTreeExpand(value, type){
      let treeList = this.organizationOptions;
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menu') {
        this.form.menuCheckStrictly = value ? true: false;
      } else if (type == 'dept') {
        this.form.deptCheckStrictly = value ? true: false;
      }
    },
    // 所有部门节点数据
    getorganizationAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.organization.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.organization.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    getPreData(){
      Promise.all([getOrganizationsSelectItems(),getDetail({roleId:this.prop.roleId})]).then(resArr =>{
        let orgData = resArr[0].data
        this.organizationOptions = this.handleTree(orgData, "organizationId","organizationParentId");
        let detailData = resArr[1].data;
        let roleOrganizations = detailData.roleOrganizations
        if(roleOrganizations){
          this.$nextTick(()=>{
            let selectKeys = roleOrganizations.map(item =>item.organizationSysCode)
            selectKeys.forEach(item =>{
              this.$refs.organization.setChecked(item,true,false);
            })
          })
        }
        detailData.roleOrganizationCheck = detailData.roleOrganizationCheck==='1'?true:false
        this.form = detailData
        this.$forceUpdate()
      }).catch(err =>{
        console.log('查询角色数据权限详细信息失败，原因：',err)
      })
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if(value !== '2') {
        this.$refs.organization.setCheckedKeys([]);
      }
    },
    /** 提交按钮（数据权限） */
    submitForm(){
      if (this.form.roleId != null) {
        let formData = this.setFormData()
        editDataScope(formData).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.cancel()
        });
      }else{
        this.$message.error('保存角色数据权限失败，请稍后再试')
      }
    },
    setFormData(){
      let roleId = this.form.roleId
      let formData = {role:{roleId:roleId,roleDataScope:this.form.roleDataScope}}
      if(formData.role.roleDataScope === '2'){
        let roleOrgs = this.getorganizationAllCheckedKeys()
        let roleOrganizations = roleOrgs.map(item =>{
          return {roleId:roleId,organizationSysCode:item}
        })
        formData.roleOrganizations = roleOrganizations
      }
      return formData
    },
    cancel() {
      this.$emit('close')
    },
  },
  mounted() {
    this.getPreData()
  }
};
</script>
<style scoped>

</style>
